// 全局变量
let currentProject = null;
let currentProjectName = '';
let projects = [];
let trainingData = [];
let queryHistory = [];

// 检查本地存储中是否有保存的项目ID
document.addEventListener('DOMContentLoaded', function() {
    const savedProjectId = localStorage.getItem('currentProjectId');
    if (savedProjectId) {
        currentProject = savedProjectId;
    }
});

// API 基础 URL
const API_BASE = '/api/v1';

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeNavigation();
    
    // 加载项目并初始化全局选择器
    loadProjects().then(() => {
        initializeGlobalProjectSelector();
    });
    
    // 初始化训练数据过滤器
    initializeTrainingDataFilters();
    
    // 添加全局项目选择器的变更事件
    document.getElementById('global-project-select').addEventListener('change', function() {
        const projectId = this.value;
        selectProject(projectId, true);
    });
});

// 导航功能
function initializeNavigation() {
    const navLinks = document.querySelectorAll('.nav-link');
    const pages = document.querySelectorAll('.page');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            pages.forEach(p => p.classList.remove('active'));
            
            // 添加活动状态
            this.classList.add('active');
            const pageId = this.dataset.page + '-page';
            document.getElementById(pageId).classList.add('active');
            
            // 根据页面加载相应数据
            switch(this.dataset.page) {
                case 'projects':
                    loadProjects();
                    break;
                case 'training':
                    loadTrainingData();
                    break;
                case 'generator':
                    // 确保生成页面的UI状态正确
                    updateProjectStatusUI();
                    break;
                case 'corrector':
                    // 确保纠错页面的UI状态正确
                    updateProjectStatusUI();
                    break;
                case 'history':
                    loadQueryHistory();
                    break;
                case 'config':
                    // 确保配置页面的UI状态正确
                    updateProjectStatusUI();
                    break;
            }
        });
    });
}

// 项目管理功能
async function loadProjects() {
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/projects`);
        if (response.ok) {
            const data = await response.json();
            projects = data.items || data; // 处理分页格式或直接数组格式
            renderProjects();
            
            // 如果有保存的项目ID，恢复选择
            if (currentProject) {
                const savedProject = projects.find(p => p.id === currentProject);
                if (savedProject) {
                    selectProject(currentProject, false);
                } else {
                    // 如果保存的项目不存在，清除保存
                    currentProject = null;
                    localStorage.removeItem('currentProjectId');
                }
            }
            
            return projects;
        } else {
            showNotification('加载项目失败', 'error');
            return [];
        }
    } catch (error) {
        console.error('加载项目错误:', error);
        showNotification('加载项目失败', 'error');
        return [];
    } finally {
        hideLoading();
    }
}

function renderProjects() {
    const grid = document.getElementById('projects-grid');
    
    if (projects.length === 0) {
        grid.innerHTML = `
            <div class="empty-state">
                <h3>暂无项目</h3>
                <p>点击"创建项目"按钮开始创建您的第一个项目</p>
            </div>
        `;
        return;
    }
    
    grid.innerHTML = projects.map(project => `
        <div class="project-card">
            <h3>${escapeHtml(project.name)}</h3>
            <p>${escapeHtml(project.description || '暂无描述')}</p>
            <div class="project-card-actions">
                <button class="btn btn-primary" onclick="selectProject('${project.id}')">选择</button>
                <button class="btn btn-danger" onclick="deleteProject('${project.id}')">删除</button>
            </div>
        </div>
    `).join('');
}

async function loadProjectsForSelect(selectId = 'project-select') {
    try {
        // 如果已经有项目数据，直接使用
        if (projects.length > 0) {
            const select = document.getElementById(selectId);
            if (select) {
                select.innerHTML = '<option value="">选择项目</option>' + 
                    projects.map(p => `<option value="${p.id}">${escapeHtml(p.name)}</option>`).join('');
                
                // 如果有当前选择的项目，设置选中
                if (currentProject) {
                    select.value = currentProject;
                }
            }
            return;
        }
        
        // 否则重新加载
        const response = await fetch(`${API_BASE}/projects`);
        if (response.ok) {
            const data = await response.json();
            const projectsList = data.items || data; // 处理分页格式或直接数组格式
            const select = document.getElementById(selectId);
            if (select) {
                select.innerHTML = '<option value="">选择项目</option>' + 
                    projectsList.map(p => `<option value="${p.id}">${escapeHtml(p.name)}</option>`).join('');
                
                // 如果有当前选择的项目，设置选中
                if (currentProject) {
                    select.value = currentProject;
                }
            }
        }
    } catch (error) {
        console.error('加载项目选择器错误:', error);
    }
}

function showCreateProjectModal() {
    document.getElementById('create-project-modal').style.display = 'block';
}

async function createProject() {
    const name = document.getElementById('project-name').value.trim();
    const description = document.getElementById('project-description').value.trim();
    
    if (!name) {
        showNotification('请输入项目名称', 'error');
        return;
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/projects`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, description })
        });
        
        if (response.ok) {
            showNotification('项目创建成功', 'success');
            closeModal('create-project-modal');
            clearProjectForm();
            loadProjects();
        } else {
            showNotification('项目创建失败', 'error');
        }
    } catch (error) {
        console.error('创建项目错误:', error);
        showNotification('项目创建失败', 'error');
    } finally {
        hideLoading();
    }
}

async function deleteProject(projectId) {
    if (!confirm('确定要删除这个项目吗？')) {
        return;
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/projects/${projectId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            showNotification('项目删除成功', 'success');
            loadProjects();
        } else {
            showNotification('项目删除失败', 'error');
        }
    } catch (error) {
        console.error('删除项目错误:', error);
        showNotification('项目删除失败', 'error');
    } finally {
        hideLoading();
    }
}

function selectProject(projectId, showNotify = true) {
    if (!projectId) {
        currentProject = null;
        currentProjectName = '';
        localStorage.removeItem('currentProjectId');
        
        // 更新UI
        updateProjectStatusUI();
        
        if (showNotify) {
            showNotification('已清除项目选择', 'info');
        }
        return;
    }
    
    const project = projects.find(p => p.id === projectId);
    if (!project) return;
    
    currentProject = projectId;
    currentProjectName = project.name;
    
    // 保存到本地存储
    localStorage.setItem('currentProjectId', projectId);
    
    // 更新所有项目选择器
    updateAllProjectSelectors(projectId);
    
    // 更新UI显示
    updateProjectStatusUI();
    
    // 根据当前页面加载相关数据
    const activePage = document.querySelector('.page.active').id;
    if (activePage === 'training-page') {
        loadTrainingData();
    } else if (activePage === 'history-page') {
        loadQueryHistory();
    }
    
    if (showNotify) {
        showNotification(`已选择项目: ${project.name}`, 'success');
    }
}

function updateAllProjectSelectors(projectId) {
    // 更新全局选择器
    const globalSelect = document.getElementById('global-project-select');
    if (globalSelect) {
        globalSelect.value = projectId;
    }
    
    // 更新所有页面的项目选择器
    const selects = ['generator-project-select', 'corrector-project-select', 'history-project-select'];
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        if (select) {
            select.value = projectId;
        }
    });
}

function updateProjectStatusUI() {
    // 更新全局项目信息显示
    const currentProjectInfo = document.getElementById('current-project-info');
    if (currentProjectInfo) {
        if (currentProject) {
            currentProjectInfo.innerHTML = `<span>当前项目: <strong>${escapeHtml(currentProjectName)}</strong></span>`;
            currentProjectInfo.style.display = 'block';
        } else {
            currentProjectInfo.innerHTML = `<span>未选择项目</span>`;
            currentProjectInfo.style.display = 'block';
        }
    }
    
    // 更新所有页面的项目状态
    const statusElements = [
        { id: 'training-project-status', btnId: 'add-training-btn' },
        { id: 'generator-project-status' },
        { id: 'corrector-project-status' },
        { id: 'history-project-status' }
    ];
    
    statusElements.forEach(item => {
        const statusEl = document.getElementById(item.id);
        if (statusEl) {
            if (currentProject) {
                statusEl.innerHTML = `<span class="status-text">当前项目: <strong>${escapeHtml(currentProjectName)}</strong></span>`;
            } else {
                statusEl.innerHTML = `<span class="status-text">请先选择项目</span>`;
            }
        }
        
        // 如果有关联的按钮，更新按钮状态
        if (item.btnId) {
            const btn = document.getElementById(item.btnId);
            if (btn) {
                btn.disabled = !currentProject;
            }
        }
    });
}

function initializeGlobalProjectSelector() {
    const globalSelect = document.getElementById('global-project-select');
    if (!globalSelect) return;
    
    // 清空现有选项
    globalSelect.innerHTML = '<option value="">选择项目</option>';
    
    // 添加所有项目
    projects.forEach(project => {
        const option = document.createElement('option');
        option.value = project.id;
        option.textContent = project.name;
        globalSelect.appendChild(option);
    });
    
    // 设置当前选中的项目
    if (currentProject) {
        globalSelect.value = currentProject;
    }
}

function clearProjectForm() {
    document.getElementById('project-name').value = '';
    document.getElementById('project-description').value = '';
}

// 训练数据功能
function initializeTrainingDataFilters() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            tabBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            filterTrainingData(this.dataset.type);
        });
    });
}

async function loadTrainingData() {
    const projectId = currentProject;
    if (!projectId) {
        document.getElementById('training-data-list').innerHTML = `
            <div class="empty-state">
                <h3>请先选择项目</h3>
                <p>选择一个项目后才能查看训练数据</p>
            </div>
        `;
        return;
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/${projectId}/training-data`);
        if (response.ok) {
            const data = await response.json();
            trainingData = data.items || [];
            renderTrainingData();
        } else {
            showNotification('加载训练数据失败', 'error');
        }
    } catch (error) {
        console.error('加载训练数据错误:', error);
        showNotification('加载训练数据失败', 'error');
    } finally {
        hideLoading();
    }
}

function renderTrainingData(filteredData = trainingData) {
    const list = document.getElementById('training-data-list');
    
    if (filteredData.length === 0) {
        list.innerHTML = `
            <div class="empty-state">
                <h3>暂无训练数据</h3>
                <p>点击"添加训练数据"按钮开始添加数据</p>
            </div>
        `;
        return;
    }
    
    list.innerHTML = filteredData.map(item => `
        <div class="training-data-item">
            <div class="training-data-header">
                <span class="training-data-type">${getTypeLabel(item.type)}</span>
                <button class="btn btn-danger" onclick="deleteTrainingData('${item.id}')">删除</button>
            </div>
            ${renderTrainingDataContent(item)}
        </div>
    `).join('');
}

function renderTrainingDataContent(item) {
    switch (item.type) {
        case 'ddl':
            return `<div class="training-data-content">${escapeHtml(item.content)}</div>`;
        case 'question_sql':
            return `
                <div style="margin-bottom: 1rem;">
                    <strong>问题:</strong> ${escapeHtml(item.question)}
                </div>
                <div class="training-data-content">${escapeHtml(item.sql)}</div>
            `;
        case 'description':
            return `<div class="training-data-content">${escapeHtml(item.content)}</div>`;
        default:
            return `<div class="training-data-content">${escapeHtml(item.content || '')}</div>`;
    }
}

function getTypeLabel(type) {
    const labels = {
        'ddl': 'DDL',
        'question_sql': '问题-SQL',
        'description': '描述'
    };
    return labels[type] || type;
}

function filterTrainingData(type) {
    if (type === 'all') {
        renderTrainingData();
    } else {
        const filtered = trainingData.filter(item => item.type === type);
        renderTrainingData(filtered);
    }
}

function showCreateTrainingDataModal() {
    if (!currentProject) {
        showNotification('请先选择项目', 'error');
        return;
    }
    document.getElementById('create-training-data-modal').style.display = 'block';
}

function toggleTrainingDataFields() {
    const type = document.getElementById('training-data-type').value;
    const contentGroup = document.getElementById('content-group');
    const questionGroup = document.getElementById('question-group');
    const sqlGroup = document.getElementById('sql-group');
    
    if (type === 'question_sql') {
        contentGroup.style.display = 'none';
        questionGroup.style.display = 'block';
        sqlGroup.style.display = 'block';
    } else {
        contentGroup.style.display = 'block';
        questionGroup.style.display = 'none';
        sqlGroup.style.display = 'none';
    }
}

async function createTrainingData() {
    const projectId = currentProject;
    if (!projectId) {
        showNotification('请先选择项目', 'error');
        return;
    }
    const type = document.getElementById('training-data-type').value;
    
    let data = { type };
    
    if (type === 'question_sql') {
        data.question = document.getElementById('training-data-question').value.trim();
        data.sql = document.getElementById('training-data-sql').value.trim();
        data.content = '';
        
        if (!data.question || !data.sql) {
            showNotification('请填写问题和SQL', 'error');
            return;
        }
    } else {
        data.content = document.getElementById('training-data-content').value.trim();
        data.question = null;
        data.sql = null;
        
        if (!data.content) {
            showNotification('请填写内容', 'error');
            return;
        }
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/${projectId}/training-data`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            showNotification('训练数据添加成功', 'success');
            closeModal('create-training-data-modal');
            clearTrainingDataForm();
            loadTrainingData();
        } else {
            showNotification('训练数据添加失败', 'error');
        }
    } catch (error) {
        console.error('添加训练数据错误:', error);
        showNotification('训练数据添加失败', 'error');
    } finally {
        hideLoading();
    }
}

async function deleteTrainingData(dataId) {
    if (!confirm('确定要删除这条训练数据吗？')) {
        return;
    }
    
    const projectId = currentProject;
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/${projectId}/training-data/${dataId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            showNotification('训练数据删除成功', 'success');
            loadTrainingData();
        } else {
            showNotification('训练数据删除失败', 'error');
        }
    } catch (error) {
        console.error('删除训练数据错误:', error);
        showNotification('训练数据删除失败', 'error');
    } finally {
        hideLoading();
    }
}

function clearTrainingDataForm() {
    document.getElementById('training-data-type').value = 'ddl';
    document.getElementById('training-data-content').value = '';
    document.getElementById('training-data-question').value = '';
    document.getElementById('training-data-sql').value = '';
    toggleTrainingDataFields();
}

// SQL生成功能
async function generateSQL() {
    const projectId = currentProject;
    const question = document.getElementById('question-input').value.trim();
    const dbType = document.getElementById('db-type-select').value;
    
    if (!projectId) {
        showNotification('请先选择项目', 'error');
        return;
    }
    
    if (!question) {
        showNotification('请输入查询问题', 'error');
        return;
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/${projectId}/text2sql`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                question,
                db_type: dbType
            })
        });
        
        if (response.ok) {
            const sql = await response.text();
            document.getElementById('generated-sql').textContent = sql;
            showNotification('SQL生成成功', 'success');
        } else {
            showNotification('SQL生成失败', 'error');
        }
    } catch (error) {
        console.error('生成SQL错误:', error);
        showNotification('SQL生成失败', 'error');
    } finally {
        hideLoading();
    }
}

function copySQLToClipboard() {
    const sql = document.getElementById('generated-sql').textContent;
    navigator.clipboard.writeText(sql).then(() => {
        showNotification('SQL已复制到剪贴板', 'success');
    }).catch(() => {
        showNotification('复制失败', 'error');
    });
}

// SQL纠错功能
async function correctSQL() {
    const projectId = currentProject;
    const question = document.getElementById('correction-question').value.trim();
    const errorSQL = document.getElementById('error-sql').value.trim();
    const errorMessage = document.getElementById('error-message').value.trim();
    const dbType = document.getElementById('corrector-db-type').value;
    
    if (!projectId) {
        showNotification('请先选择项目', 'error');
        return;
    }
    
    if (!question || !errorSQL || !errorMessage) {
        showNotification('请填写所有必要信息', 'error');
        return;
    }
    
    try {
        showLoading();
        const response = await fetch(`${API_BASE}/${projectId}/correct`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                question,
                error_attempts: [{
                    sql: errorSQL,
                    error_message: errorMessage
                }],
                db_type: dbType
            })
        });
        
        if (response.ok) {
            const correctedSQL = await response.text();
            document.getElementById('corrected-sql').textContent = correctedSQL;
            showNotification('SQL纠错成功', 'success');
        } else {
            showNotification('SQL纠错失败', 'error');
        }
    } catch (error) {
        console.error('纠错SQL错误:', error);
        showNotification('SQL纠错失败', 'error');
    } finally {
        hideLoading();
    }
}

function copyCorrectedSQLToClipboard() {
    const sql = document.getElementById('corrected-sql').textContent;
    navigator.clipboard.writeText(sql).then(() => {
        showNotification('纠正后的SQL已复制到剪贴板', 'success');
    }).catch(() => {
        showNotification('复制失败', 'error');
    });
}

// 查询历史功能
async function loadQueryHistory() {
    const projectId = currentProject;
    if (!projectId) {
        document.getElementById('history-list').innerHTML = `
            <div class="empty-state">
                <h3>请先选择项目</h3>
                <p>选择一个项目后才能查看查询历史</p>
            </div>
        `;
        return;
    }
    
    const typeFilter = document.getElementById('history-type-filter').value;
    let url = `${API_BASE}/${projectId}/history`;
    if (typeFilter) {
        url += `?type=${typeFilter}`;
    }
    
    try {
        showLoading();
        const response = await fetch(url);
        if (response.ok) {
            const data = await response.json();
            queryHistory = data.items || [];
            renderQueryHistory();
        } else {
            showNotification('加载查询历史失败', 'error');
        }
    } catch (error) {
        console.error('加载查询历史错误:', error);
        showNotification('加载查询历史失败', 'error');
    } finally {
        hideLoading();
    }
}

function renderQueryHistory() {
    const list = document.getElementById('history-list');
    
    if (queryHistory.length === 0) {
        list.innerHTML = `
            <div class="empty-state">
                <h3>暂无查询历史</h3>
                <p>开始使用SQL生成或纠错功能后，历史记录将显示在这里</p>
            </div>
        `;
        return;
    }
    
    list.innerHTML = queryHistory.map(item => `
        <div class="history-item">
            <div class="history-header">
                <span class="history-type ${item.type}">${getHistoryTypeLabel(item.type)}</span>
                <span>${formatDate(item.created_at)}</span>
            </div>
            <div class="history-question">${escapeHtml(item.question)}</div>
            <div class="history-sql">${escapeHtml(item.generated_sql)}</div>
            ${item.error_sql ? `<div style="margin-top: 0.5rem; color: #dc3545; font-size: 0.9rem;">错误SQL: ${escapeHtml(item.error_sql)}</div>` : ''}
            ${item.error_message ? `<div style="margin-top: 0.5rem; color: #dc3545; font-size: 0.9rem;">错误信息: ${escapeHtml(item.error_message)}</div>` : ''}
        </div>
    `).join('');
}

function getHistoryTypeLabel(type) {
    const labels = {
        'generation': 'SQL生成',
        'correction': 'SQL纠错'
    };
    return labels[type] || type;
}

// 监听过滤器变化
document.addEventListener('change', function(e) {
    if (e.target.id === 'history-type-filter') {
        loadQueryHistory();
    }
});

// 工具函数
function showModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function showLoading() {
    document.getElementById('loading').style.display = 'flex';
}

function hideLoading() {
    document.getElementById('loading').style.display = 'none';
}

function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    const messageEl = document.getElementById('notification-message');
    
    messageEl.textContent = message;
    notification.className = `notification ${type}`;
    notification.style.display = 'block';
    
    setTimeout(() => {
        closeNotification();
    }, 3000);
}

function closeNotification() {
    document.getElementById('notification').style.display = 'none';
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
}